package com.luoxue.execsql.rest.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luoxue.execsql.common.contact.ExecSqlContact;
import com.luoxue.execsql.common.util.ResultBody;
import com.luoxue.execsql.rest.bean.base.controller.BaseController;
import com.luoxue.execsql.rest.bean.datasource.DynamicDataSource;
import com.luoxue.execsql.rest.entity.SysDataSource;
import com.luoxue.execsql.rest.mapper.DataSourceMapper;
import com.luoxue.execsql.rest.service.IDataSourceService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@RestController
@RequestMapping("/dataSource")
public class DataSourceController extends BaseController<SysDataSource, DataSourceMapper, IDataSourceService> {

    @Resource
    DynamicDataSource dynamicDataSource;

    public DataSourceController(IDataSourceService service) {
        super(service);
    }

    @Override
    protected void queryParams(SysDataSource entity, QueryWrapper<SysDataSource> queryWrapper) {
        if (entity.getId() != null) {
            queryWrapper.lambda().like(SysDataSource::getId, entity.getId());
        }
        if (Strings.isNotBlank(entity.getDataSourceName())) {
            queryWrapper.lambda().like(SysDataSource::getDataSourceName, entity.getDataSourceName());
        }
        queryWrapper.orderByDesc("update_time", "id");
    }

    @GetMapping("/allList")
    protected Mono<ResultBody> allList() {
        return Mono.just(ResultBody.ok(service.list()));
    }

    @Override
    public Mono<ResultBody> save(@RequestBody SysDataSource entity) {
        try {
            dynamicDataSource.updateTargetDataSource(entity);
            return super.save(entity);
        } catch (DuplicateKeyException e) {
            return Mono.just(ResultBody.error("数据源名已存在"));
        }
    }

    @Override
    public Mono<ResultBody> updateById(@RequestBody SysDataSource entity) {
        try {
            dynamicDataSource.updateTargetDataSource(entity);
            return super.updateById(entity);
        } catch (DuplicateKeyException e) {
            return Mono.just(ResultBody.error("数据源名已存在"));
        }
    }

    @Override
    public Mono<ResultBody> removeById(Long id) {
        dynamicDataSource.deleteTargetDataSource(service.getById(id));
        return super.removeById(id);
    }
}
